package exams.concurrent;

import java.util.*;
import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CallableSolution implements Callable<Integer> {

    private final int start;

    private final int end;

    private Lock lock = new ReentrantLock();

    public CallableSolution(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) {
        final long TOTAL = 1000;
        final int CHUNK_SIZE = 100;

        List<Future<Integer>> futureList = new ArrayList<>();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 1; i <= TOTAL; i += CHUNK_SIZE) {
            CallableSolution callableSolution = new CallableSolution(i, i+CHUNK_SIZE - 1);
            futureList.add(executorService.submit(callableSolution));
        }

        int res = 0;
        try {
            for(Future<Integer> future: futureList) {
                res += future.get();
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(res);
    }

    @Override
    public Integer call() throws Exception {
        int res = 0;
        for(int i=start; i<=end; i++) {
            res += i;
        }
        return res;
    }

}
